package com.reyi.book.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.reyi.book.mapper.TUserMapper;
import com.reyi.book.pojo.Ranking;
import com.reyi.book.pojo.TUser;
import com.reyi.book.pojo.TUserExample;

@Service
public class IndexServiceImpl implements IndexService{
	
	@Autowired
	private TUserMapper userMapper;

	
	//根据用户名返回用户对象
	@Override
	public TUser selectUserByUid(String uid) {
		TUserExample example  = new TUserExample();
		example.createCriteria().andUidEqualTo(uid);
		List<TUser> users = userMapper.selectByExample(example);
		if (users.size()!=0) {
			System.err.println("长度是"+users.size());
			return users.get(0);
		}
		return null;
	}

	@Override
	public boolean insertUser(TUser user) {
		userMapper.insert(user);
		return false;
	}

	@Override
	public boolean updateUser(TUser user) {
		userMapper.updateByPrimaryKey(user);
		return true;
	}

	@Override
	public List<Ranking> fetchRanking() {
		TUserExample example = new TUserExample();
		example.createCriteria().andUidIsNotNull();
		List<TUser> users = userMapper.selectByExample(example);
		Collections.sort(users);
		List<Ranking> backList = new ArrayList<>();
		for (TUser tUser : users) {
			Ranking ranking = new Ranking();
			ranking.setName(tUser.getNickname());
			ranking.setPassNum(tUser.getFinishedWeek()+"");
			ranking.setFlag(false);
			ranking.setPraiseNum(tUser.getLikeWeek());
			backList.add(ranking);
		}
		return backList;
	}

	@Override
	public boolean updateLikeNum(String nickname, int num) {
		TUserExample example =  new TUserExample();
		example.createCriteria().andNicknameEqualTo(nickname);
		TUser user = userMapper.selectByExample(example).get(0);
		user.setLikeWeek(num);
		userMapper.updateByPrimaryKey(user);
		return true;
	}

}
